import dayjs from "dayjs";
import editForm from "../form.vue";
// import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { ElMessageBox, ElMessage } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import {
  deviceDetection,
  downloadByOnlineUrl,
  storageLocal
} from "@pureadmin/utils";
import type { PaginationProps } from "@pureadmin/table";
import {
  getVideoList,
  addVideo,
  updateVideo,
  deleteVideo,
  sendVideo,
  getExist,
  getLabel
} from "@/api/javlist";
import { type Ref, reactive, ref, onMounted, h, toRaw, watch } from "vue";
import { Icon as IconifyIcon } from "@iconify/vue";

export function avVideo(treeRef: Ref) {
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 15,
    pageSizes: [15, 30, 50, 75, 100],
    currentPage: 1,
    background: true,
    size: "small"
  });

  const form = reactive({
    title: "",
    code: "",
    status: "",
    currentPage: pagination.currentPage,
    pageSize: pagination.pageSize,
    label: "",
    series: ""
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const choosedTasks = ref([]);
  // const treeIds = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const treeSearchValue = ref();
  const switchLoadMap = ref({});
  // const isExpandAll = ref(false);
  // const isSelectAll = ref(false);

  const showHistory = ref(false);
  const searchHistory = ref([]);
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };
  const columns: TableColumnList = [
    {
      type: "selection",
      align: "center",
      minWidth: 8
    },
    {
      label: "编号",
      prop: "id",
      sortable: true,
      minWidth: 38
    },
    {
      label: "套图ID",
      prop: "status",
      sortable: true,
      minWidth: 52,
      cellRenderer: ({ row }) => (
        <div class="width: 30px; hight: 30px">
          <span>
            <div>
              <span
                class="cursor-pointer hover:text-red-500 hover:font-bold"
                v-copy:click={row.linkid}
              >
                {row.linkid}
              </span>
            </div>
            <div>
              <span
                class="cursor-pointer hover:text-red-500 hover:font-bold"
                v-copy:click={row.av_id}
              >
                {row.av_id}
              </span>
            </div>
          </span>
        </div>
      )
    },
    {
      label: "标题",
      prop: "title",
      sortable: true,
      minWidth: 120,
      align: "left"
    },
    {
      label: "明星",
      prop: "len",
      sortable: true,
      minWidth: 38,
      cellRenderer: ({ row }) => (
        <div class="width: 30px; hight: 30px">
          <div>
            <el-tag v-show={row.stars} class="el-tag--divide-amber-500">
              {row.stars}
            </el-tag>
          </div>
        </div>
      )
    },
    {
      label: "M3U8",
      minWidth: 20,
      align: "center",
      cellRenderer: ({ row }) => (
        <div class="width: 30px; hight: 30px;">
          <span
            v-show={row.m3u8}
            class="cursor-pointer hover:text-sky-600 hover:font-bold"
            title={row.m3u8}
            v-copy:click={row.m3u8 || " "}
          >
            <IconifyIcon class="w-6 h-6" icon="arcticons:m3u" />
          </span>
          <span
            v-show={row.magnet}
            class="cursor-pointer hover:text-green-600 hover:font-bold"
            title={row.m3u8}
            v-copy:click={row.magnet || " "}
          >
            <IconifyIcon class="w-6 h-6" icon="ep:magnet" />
          </span>
        </div>
      )
    },
    {
      label: "预览",
      prop: "tags",
      minWidth: 30,
      cellRenderer: ({ row }) => (
        <el-popover
          effect="light"
          trigger="hover"
          placement="left"
          width="auto"
        >
          {{
            default: () => (
              <>
                <img
                  v-show={row.bigimage}
                  src={row.bigimage}
                  style="height: 300px; width: auto;"
                />
              </>
            ),
            reference: () => (
              <el-image
                preview-teleported
                loading="lazy"
                src={row.bigimage}
                style="height: 30px; width: 48px"
                fit="cover"
              />
            )
          }}
        </el-popover>
      )
    },
    {
      label: "类别",
      prop: "status",
      sortable: true,
      minWidth: 40,
      cellRenderer: ({ row }) => (
        <div class="width: 30px; hight: 30px">
          <div>
            <el-tag class="el-tag--success el-tag--light">{row.label}</el-tag>
          </div>
          <div>
            <el-tag class="el-tag--divide-amber-500 mb-2">{row.series}</el-tag>
          </div>
        </div>
      )
    },
    {
      label: "状态",
      minWidth: 40,
      sortable: true,
      cellRenderer: scope => (
        <el-switch
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="有"
          inactive-text="无"
          inline-prompt
          // style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "创建",
      minWidth: 34,
      sortable: true,
      prop: "release_date",
      cellRenderer: ({ row }) => (
        <div>
          <div>{row.len}</div>
          <div>{row.release_date}</div>
        </div>
      )
      // formatter: ({ release_date }) => dayjs(release_date).format("YYYY-MM-DD")
    },
    {
      label: "操作",
      fixed: "right",
      width: 170,
      slot: "operation"
    }
  ];
  function onChange({ row }) {
    const result: any = editVideo(row);
    seedMessage(result, row.av_id);
  }

  function handleDelete(row) {
    delVideo(row);
    message(`您删除了${row.title}的这条数据`, { type: "success" });
    onSearch();
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    form.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
    choosedTasks.value = val;
  }

  function addExist(val) {
    console.log("addExist", val);
    const dataList = choosedTasks.value;
    for (let i = 0; i < dataList.length; i++) {
      const curData = toRaw(dataList[i]);
      if (curData.status !== 1) {
        curData.status = 1;
        const result = editVideo(curData);
        seedMessage(result, curData.av_id);
      }
      onSearch();
    }
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getVideoList(toRaw(form));
    dataList.value = data.list;
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.currentPage;
    handleSearch();

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  async function newVideo(curData) {
    loading.value = true;
    delete curData.id;
    const { data } = await addVideo(toRaw(curData));
    console.log("addVideo返回数据:", data);
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  async function editVideo(curData) {
    loading.value = true;
    // console.log("curData:", curData);
    // delete curData.m3u8;
    // delete curData.bigimage;
    const { data } = await updateVideo(toRaw(curData));
    // console.log("editVideo返回数据:", data);
    setTimeout(() => {
      loading.value = false;
    }, 500);
    return data;
  }

  async function delVideo(curData) {
    loading.value = true;
    const { data } = await deleteVideo(toRaw(curData));
    console.log("delVideo返回数据:", data);
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  /** 发送 单条数据至API下载 */
  async function avGain(curData, host: string) {
    console.log("curData:", toRaw(curData));
    // console.log("curData.label:", toRaw(curData).label);
    const m3u8Dom = toRaw(curData) || "";
    const m3u8Url = toRaw(curData).m3u8;

    const title = m3u8Dom.title.replace(",", " ").substring(0, 70);

    // console.log("title m3u8Url:", title, m3u8Url);
    if (m3u8Url && title) {
      const sendData = { data: `${title}, ${m3u8Url}`, type: 2 };
      // console.log("sendData:", sendData);
      const cur = toRaw(curData);
      console.log("cur.status:", cur.status);
      // console.log("cur:", cur);

      const totalResults = await avIDRefresh(cur);
      // console.log("totalResults:", totalResults);
      if ((cur.status & totalResults) == 0) {
        cur.status = 1;
        seedMessage(editVideo(cur), cur.av_id);
        onSearch();
        // console.log("cur.status & totalResults");
        if (totalResults == 0) {
          console.log("totalResults == 0");
          sendVideo(host, sendData);
        }
      } else {
        console.log("else");
        ElMessageBox.confirm(
          `确认要<strong>${
            cur.status === 0 ? "停用" : "下载"
          }</strong><strong style='color:var(--el-color-primary)'>${
            cur.av_id
          }</strong>吗?`,
          "下载提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            dangerouslyUseHTMLString: true,
            draggable: true
          }
        )
          .then(() => {
            sendVideo(host, sendData);
          })
          .catch(() => {
            ElMessage({
              message: `${title} 已存在`,
              type: "warning"
            });
          });
      }
    }
  }

  /** 批量下载预览图片 */
  function downPreview(val) {
    console.log("batchDown", val);
    const dataList = choosedTasks.value;
    console.log("dataList", dataList);
    for (let i = 0; i < dataList.length; i++) {
      const curData = toRaw(dataList[i]);
      console.log("curData", curData);
      const title =
        curData.title +
        "." +
        curData.bigimage.substring(curData.bigimage.lastIndexOf(".") + 1);
      console.log("title:", title);
      // downLoadPreview(curData.bigimage, title);
      downloadByOnlineUrl(curData.bigimage, title);
    }
  }

  /** 发送 批量数据至API下载 */
  function batchDown(val) {
    console.log("batchDown", val);
    const dataList = choosedTasks.value;
    console.log("dataList", dataList);
    for (let i = 0; i < dataList.length; i++) {
      const curData = toRaw(dataList[i]);
      console.log("curData", curData);
      if (curData.status !== 1) {
        curData.status = 1;
        setTimeout(() => {
          avGain(curData, val);
        }, 1000);
      }
    }
  }

  /** 检测 批量数据存在 */
  function avRefresh(row: any) {
    const dataList = choosedTasks.value;
    console.log("dataList", dataList);
    for (let i = 0; i < dataList.length; i++) {
      const curData = toRaw(dataList[i]);
      console.log("curData", curData);
      avIDRefresh(curData);
    }
  }

  /** 检测 单条数据存在 */
  async function avIDRefresh(row: any) {
    const curData = toRaw(row);
    console.log("curData Exist:", curData);
    const extend = ".mp4|.avi|.ts|.mkv|.wmv";
    const seedData = `m3u8/?search=${curData.av_id} ${extend}&json=1`;
    const result: any = await getExist(seedData);
    const totalResults = result.totalResults;
    console.log("curData:", curData.status);
    console.log("totalResults:", totalResults);
    // delete curData.m3u8;
    // delete curData.bigimage;
    const curStatus = curData.status;
    curData.status = totalResults == 0 ? 0 : 1;
    if (curStatus !== curData.status) {
      setTimeout(() => {
        seedMessage(editVideo(curData), curData.av_id);
      }, 500);
      onSearch();
    }
    ElMessage({
      message: `${curData.av_id} ${totalResults >= 1 ? "已存在" : "不存在"}`,
      type: totalResults == 1 ? "success" : "error"
    });
    return totalResults;
  }

  /** 消息弹出 */
  function seedMessage(result, av_id) {
    result.then(result => {
      // console.log("result", result, typeof result);
      ElMessage({
        message: `${av_id} 已更新`,
        type: result
      });
    });
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "new", row?: FormItemProps) {
    addDialog({
      title: `${title}角色`,
      props: {
        formInline: {
          id: row?.id ?? "",
          linkid: row?.linkid ?? "",
          title: row?.title ?? "",
          av_id: row?.av_id ?? "",
          release_date: row?.release_date ?? "",
          len: row?.len ?? "",
          director: row?.director ?? "",
          studio: row?.studio ?? "",
          label: row?.label ?? "",
          series: row?.series ?? "",
          genre: row?.genre ?? "",
          stars: row?.stars ?? "",
          director_url: row?.director_url ?? "",
          studio_url: row?.studio_url ?? "",
          label_url: row?.label_url ?? "",
          series_url: row?.series_url ?? "",
          stars_url: row?.stars_url ?? "",
          bigimage: row?.bigimage ?? "",
          image_len: row?.image_len ?? "",
          m3u8: row?.m3u8 ?? "",
          magnet: row?.magnet ?? "",
          status: row?.status ?? ""
        }
      },
      width: "60%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了${curData.title}的数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              console.log("弹窗新增title:", title);
              newVideo(curData);
              chores();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              console.log("弹窗修改title:", title);
              editVideo(curData);
              chores();
            }
          }
        });
      }
    });
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: "pointer",
      background: id === curRow.value?.id ? "var(--el-fill-color-light)" : ""
    };
  }

  /** 菜单权限-保存 */
  // function handleSave() {
  //   const { id, name } = curRow.value;
  //   // 根据用户 id 调用实际项目中菜单权限修改接口
  //   console.log(id, treeRef.value.getCheckedKeys());
  //   message(`角色名称为${name}的菜单权限修改成功`, {
  //     type: "success"
  //   });
  // }

  /** 数据权限 可自行开发 */
  // function handleDatabase() {}

  // const onQueryChanged = (query: string) => {
  //   treeRef.value!.filter(query);
  // };

  const getSearch = () => {
    const history: string = storageLocal().getItem("searchHistory");
    if (history) {
      searchHistory.value = JSON.parse(history);
    }
  };

  // 处理搜索
  const handleSearch = () => {
    if (form.title.trim()) {
      // 避免重复添加
      if (!searchHistory.value.includes(form.title)) {
        searchHistory.value.unshift(form.title);
        // 限制历史记录数量
        if (searchHistory.value.length > 100) {
          searchHistory.value.pop();
        }
        // 保存到本地存储
        storageLocal().setItem(
          "searchHistory",
          JSON.stringify(searchHistory.value)
        );
      }
      showHistory.value = false;
      // 这里可以添加实际的搜索逻辑
      console.log("搜索:", form.title);
    }
  };

  // 选择历史记录
  const selectHistory = item => {
    form.title = item;
    handleSearch();
  };

  // 删除单条历史记录
  const removeHistory = index => {
    searchHistory.value.splice(index, 1);
    storageLocal().setItem(
      "searchHistory",
      JSON.stringify(searchHistory.value)
    );
  };

  // 清空历史记录
  const clearHistory = () => {
    searchHistory.value = [];
    storageLocal().removeItem("searchHistory");
  };

  // 处理输入框失去焦点
  const handleBlur = () => {
    // 使用 setTimeout 避免点击历史项前下拉菜单就关闭了
    setTimeout(() => {
      showHistory.value = false;
    }, 200);
  };

  // 展开历史记录
  const expandHistory = () => {
    showHistory.value = true;
  };

  // const fetchChildOptions = "";
  async function getLabelOptions(val: string) {
    console.log("val:", val);
    const row = { label: val };
    const data = await getLabel(row);
    console.log("data:", data.result);
    return data.result;
  }

  onMounted(async () => {
    onSearch();
    getSearch();
    // const { data } = await getRoleMenu();
    // treeIds.value = getKeyList(data, "id");
    // treeData.value = handleTree(data);
  });

  // watch(isExpandAll, val => {
  //   val
  //     ? treeRef.value.setExpandedKeys(treeIds.value)
  //     : treeRef.value.setExpandedKeys([]);
  // });

  // watch(isSelectAll, val => {
  //   val
  //     ? treeRef.value.setCheckedKeys(treeIds.value)
  //     : treeRef.value.setCheckedKeys([]);
  // });

  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,
    // treeData,
    treeProps,
    isLinkage,
    pagination,
    // isExpandAll,
    // isSelectAll,
    treeSearchValue,
    showHistory,
    searchHistory,
    onSearch,
    getSearch,
    handleSearch,
    selectHistory,
    removeHistory,
    clearHistory,
    getLabelOptions,
    handleBlur,
    expandHistory,
    avGain,
    avRefresh,
    avIDRefresh,
    addExist,
    downPreview,
    batchDown,
    resetForm,
    openDialog,
    // handleSave,
    handleDelete,
    // onQueryChanged,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
